

package cn.shengchao.controler.query;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.shengchao.examstar.product.acl.ports.repositories.ISpecificationTypeRepository;
import cn.shengchao.examstar.product.infrastructure.dao.po.TSpecificationType;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Tag(name = "产品规格类型")
@Slf4j
@RestController
@CrossOrigin("${project.cross-origin}")
@RequestMapping("/api/${project.version}/specificationType")
public class SpecificationTypeController {
    @Autowired
    private ISpecificationTypeRepository iSpecificationTypeRepository;

    @SaIgnore
    @GetMapping()
    public List<TSpecificationType> getSpecificationTypeList(@RequestParam(defaultValue = "0") Long pid,
                                                             @RequestParam(defaultValue = "wxb939871218e622d0") String appid,
                                                             @RequestParam(defaultValue = "false")boolean isKnowledge
    ) {
        return iSpecificationTypeRepository.getSpecificationTypeList(pid, appid);
    }
   
    @SaIgnore
    @GetMapping("/tree")
    public List<Map<String, Object>> getSpecificationTypeTree(@RequestParam(defaultValue = "wxb939871218e622d0") String appid) {
        List<TSpecificationType> allTypes = iSpecificationTypeRepository.getSpecificationTypeList(null, appid);
        // 找出所有顶级节点（父ID为0或null的节点）
        List<TSpecificationType> rootTypes = allTypes.stream()
                .filter(type -> type.getParentId() == 0)
                .collect(Collectors.toList());
        // 构建树结构
        return buildTypeTree(rootTypes, allTypes);
    }
    
    private List<Map<String, Object>> buildTypeTree(List<TSpecificationType> rootTypes, List<TSpecificationType> allTypes) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (TSpecificationType rootType : rootTypes) {
            Map<String, Object> node = new HashMap<>();
            node.put("id", rootType.getId());
            node.put("name", rootType.getName());
            
            // 查找当前节点的所有子节点
            List<TSpecificationType> children = allTypes.stream()
                    .filter(type -> rootType.getId().equals(type.getParentId()))
                    .collect(Collectors.toList());
            
            // 如果有子节点，递归构建子树
            if (!children.isEmpty()) {
                node.put("children", buildTypeTree(children, allTypes));
            }
            result.add(node);
        }
        
        return result;
    }
}
